package org.oc.qaq.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Slf4j
@Component
public class JwtUtil {

    @Value("${qaq.jwt.user-secret-key}")
    private String secretKey;

    @Value("${qaq.jwt.user-ttl}")
    private Integer ttlMillis;

    public String generateToken(UserDetails userDetails) {

        // 生成JWT的时间
        long expMillis = System.currentTimeMillis() + ttlMillis;
        Date exp = new Date(expMillis);

        JwtBuilder builder = Jwts.builder()
                .subject(userDetails.getUsername())
                // 设置私有声明
                .claim("roles", userDetails.getAuthorities())
                // 签名
                .signWith(Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8)))
                // 设置过期时间
                .expiration(exp);

        return builder.compact();
    }

    public Claims extractClaims(String token) {
        // 设置签名密钥
        SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));

        return Jwts.parser()
                .verifyWith(key)
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }

    // 验证JWT令牌是否有效
    public boolean validateToken(String token, String username) {
        final String extractedUsername = extractClaims(token).getSubject();
        log.info("验证用户 {} JWT是否有效...", extractedUsername);
        return (extractedUsername.equals(username) && !isTokenExpired(token));
    }

    // 检查令牌是否过期
    private boolean isTokenExpired(String token) {
        return extractClaims(token).getExpiration().before(new Date());
    }
}
